package com.easylinkin.linkappapi.afterloan.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.afterloan.entity.AfterloanEnterpriseinfo;
import com.easylinkin.linkappapi.afterloan.entity.AfterloanRiskNumber;
import com.easylinkin.linkappapi.afterloan.entity.AfterloanRiskType;
import com.easylinkin.linkappapi.afterloan.mapper.AfterloanEnterpriseinfoMapper;
import com.easylinkin.linkappapi.afterloan.service.AfterloanEnterpriseinfoService;
import com.easylinkin.linkappapi.afterloan.service.AfterloanRiskNumberService;
import com.easylinkin.linkappapi.afterloan.service.AfterloanRiskTypeService;
import com.easylinkin.linkappapi.afterloan.utils.HttpUtils;
import com.easylinkin.linkappapi.analyze.entity.AnalyzeDateSource;
import com.easylinkin.linkappapi.analyze.service.AnalyzeDateSourceService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.elasticsearch.entity.BankAlarmNotice;
import com.easylinkin.linkappapi.elasticsearch.entity.ESconfig;
import com.easylinkin.linkappapi.elasticsearch.mapper.BankAlarmNoticeMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.Data;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@Service
public class AfterloanEnterpriseinfoServiceImpl extends ServiceImpl<AfterloanEnterpriseinfoMapper, AfterloanEnterpriseinfo> implements AfterloanEnterpriseinfoService {
    @Value("${linkapp.openReceiving:true}")
    private Boolean openReceiving;
    @Resource
    LinkappUserContextProducer linkappUserContextProducer;
    @Resource
    BankAlarmNoticeMapper bankAlarmNoticeMapper;
    @Resource
    AfterloanRiskTypeService afterloanRiskTypeService;
    @Resource
    AfterloanRiskNumberService afterloanRiskNumberService;
    @Resource
    AnalyzeDateSourceService analyzeDateSourceService;
    private  static String indexStrES = "afterloan";//test
    private  static String dataTypeES = "data_";
    private  static String DETAILS="details";
    private  static String TENANTID="tenantId";
    private static String ENTERPRISEID="enterpriseId";
    private static String ID="Id";
    private ESconfig eSconfig;
    @Autowired
    public void setESconfig(ESconfig eSconfig) {
        this.eSconfig = eSconfig;
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(AfterloanEnterpriseinfoServiceImpl.class);


    @Override
    public List<AfterloanEnterpriseinfo> getAll(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        if(afterloanEnterpriseinfo!= null){
            if(afterloanEnterpriseinfo.getTenantId() == null){
                LinkappUser user = linkappUserContextProducer.getCurrent();
                if (user != null && user.getTenantId() != null) {
                    afterloanEnterpriseinfo.setTenantId(user.getTenantId());
                }
            }
        }
        return baseMapper.getAfterloanEnterpriseinfo(afterloanEnterpriseinfo);
    }
    public List<AfterloanEnterpriseinfo> getAll(Page page,AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        if(afterloanEnterpriseinfo!= null){
            if(afterloanEnterpriseinfo.getTenantId() == null){
                afterloanEnterpriseinfo.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
            }
        }
        return baseMapper.getAfterloanEnterpriseinfo(page,afterloanEnterpriseinfo);
    }

    @Override
    public AfterloanEnterpriseinfo getAfterloanEnterpriseinfo(String name){
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        QueryWrapper<AfterloanEnterpriseinfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("tenant_id",tenantId);
        queryWrapper.eq("enterprise_name",name);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrSave(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        afterloanEnterpriseinfo.setTenantId(tenantId);
        if(StringUtils.isEmpty(afterloanEnterpriseinfo.getId())){
            Assert.notNull(afterloanEnterpriseinfo.getEnterpriseName(),"enterpriseName 不能为空");
            QueryWrapper<AfterloanEnterpriseinfo> qw=new QueryWrapper<>();
            qw.eq("enterprise_name",afterloanEnterpriseinfo.getEnterpriseName());
            qw.eq("tenant_id",tenantId);
            int count=baseMapper.selectCount(qw);
            Assert.isTrue(count<=0,"该企业已存在！");
            //新增
            Date date=new Date();
            afterloanEnterpriseinfo.setCreateTime(date);
            afterloanEnterpriseinfo.setModifyTime(date);
            afterloanEnterpriseinfo.setCreator(tenantId);
            afterloanEnterpriseinfo.setModifier(tenantId);
            save(afterloanEnterpriseinfo);

            //关联数据
            //getEnterpriseRelationRisk(afterloanEnterpriseinfo);
         return;
        }
        Assert.notNull(afterloanEnterpriseinfo.getDataSourceId(),"dataSourceId 不能为空");
        //修改数据源
        UpdateWrapper<AfterloanEnterpriseinfo> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("tenant_id",afterloanEnterpriseinfo.getTenantId());
        updateWrapper.eq("id",afterloanEnterpriseinfo.getId());
        updateWrapper.set("data_source_id",afterloanEnterpriseinfo.getDataSourceId());
        update(updateWrapper);
        return;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        Assert.notNull(afterloanEnterpriseinfo,"参数不能为空");
        Assert.notNull(afterloanEnterpriseinfo.getIds(),"ids 不能为空");
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        afterloanEnterpriseinfo.setTenantId(tenantId);
        baseMapper.deleteBatchIds(afterloanEnterpriseinfo.getIds());
        deleteEsDateByTypeAndEnterpriseIdOrDetails(afterloanEnterpriseinfo);
        //删除数据
        QueryWrapper<AfterloanRiskNumber> qw=new QueryWrapper<>();
        qw.eq("tenant_id",tenantId);
        qw.in("enterprise_id",afterloanEnterpriseinfo.getIds());
        afterloanRiskNumberService.remove(qw);
    }

    @Override
    public List<AfterloanEnterpriseinfo> getTypeAll(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        Assert.notNull(afterloanEnterpriseinfo,"参数不能为空");
        List<AfterloanEnterpriseinfo> afterloanEnterpriseinfoList=this.getAll(afterloanEnterpriseinfo);
        if(afterloanEnterpriseinfoList == null || afterloanEnterpriseinfoList.size()<=0){
            return null;
        }
        afterloanEnterpriseinfoList.stream().forEach(item->{
            Integer weekCount=null,monthCount=null;
            //1周 2 月
            if(!StringUtils.isEmpty(item.getDataSourceId())) {
                QueryWrapper<BankAlarmNotice> wrapper = new QueryWrapper<>();
                wrapper.eq("data_source_id", item.getDataSourceId());
                wrapper.eq("alarm_type", 1);
                wrapper.orderByDesc("alarm_date");
                weekCount = bankAlarmNoticeMapper.selectCount(wrapper);
                item.setWeekCount(weekCount);
                //月
                wrapper = new QueryWrapper<>();
                wrapper.eq("data_source_id", item.getDataSourceId());
                wrapper.eq("alarm_type", 2);
                wrapper.orderByDesc("alarm_date");
                monthCount = bankAlarmNoticeMapper.selectCount(wrapper);
                item.setMonthCount(monthCount);
            }
            if(weekCount == null){
                item.setWeekCount(0);
            }
            if(monthCount == null){
                item.setMonthCount(0);
            }
        });
        return afterloanEnterpriseinfoList;
    }

    @Override
    public Page getTypeAll(Page page, AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        Assert.notNull(afterloanEnterpriseinfo,"参数不能为空");
        List<AfterloanEnterpriseinfo> afterloanEnterpriseinfoList=this.getAll(page,afterloanEnterpriseinfo);
        if(afterloanEnterpriseinfoList == null || afterloanEnterpriseinfoList.size()<=0){
            return page;
        }
        afterloanEnterpriseinfoList.stream().forEach(item->{
            //1周 2 月
            Integer weekCount=null,monthCount=null;
            if(!StringUtils.isEmpty(item.getDataSourceId())){
            QueryWrapper<BankAlarmNotice> wrapper=new QueryWrapper<>();
            wrapper.eq( "data_source_id", item.getDataSourceId());
            wrapper.eq("alarm_type", 1);
            wrapper.orderByDesc("alarm_date");
             weekCount=bankAlarmNoticeMapper.selectCount(wrapper);
            item.setWeekCount(weekCount);
            //月
            wrapper=new QueryWrapper<>();
            wrapper.eq( "data_source_id", item.getDataSourceId());
            wrapper.eq("alarm_type", 2);
            wrapper.orderByDesc("alarm_date");
            monthCount=bankAlarmNoticeMapper.selectCount(wrapper);
            item.setMonthCount(monthCount);
            }
            if(weekCount == null){
                item.setWeekCount(0);
            }
            if(monthCount == null){
                item.setMonthCount(0);
            }
        });
        page.setRecords(afterloanEnterpriseinfoList);
        return page;
    }

    @Override
    public IPage getMonitor(Page page, AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        Assert.notNull(afterloanEnterpriseinfo,"参数不能为空！");
        Assert.notNull(afterloanEnterpriseinfo.getAlarmType(),"alarmType 不能为空！");
        Assert.notNull(afterloanEnterpriseinfo.getDataSourceId(),"dataSourceId 不能为空！");
        if(page == null){
            page=new Page(1,10);
        }
        //1周 2 月
        QueryWrapper<BankAlarmNotice> wrapper=new QueryWrapper<>();
        wrapper.eq( "data_source_id", afterloanEnterpriseinfo.getDataSourceId());
        wrapper.eq("alarm_type", afterloanEnterpriseinfo.getAlarmType());
        wrapper.orderByDesc("alarm_date");
       IPage<BankAlarmNotice> iPage=bankAlarmNoticeMapper.selectPage(page,wrapper);
       List<BankAlarmNotice> bankAlarmNoticeList=iPage.getRecords();
       if(bankAlarmNoticeList == null || bankAlarmNoticeList.size()<=0){
           return iPage;
       }
       //添加数据源名称
        AnalyzeDateSource analyzeDateSource=analyzeDateSourceService.getById(afterloanEnterpriseinfo.getDataSourceId());
       if(analyzeDateSource != null){
           bankAlarmNoticeList=bankAlarmNoticeList.stream().map(item->item.setDataSourceName(analyzeDateSource.getDatasourceName())).collect(Collectors.toList());
       }
        iPage.setRecords(bankAlarmNoticeList);
        return iPage;
    }

    /****
     * ==========================以下为企查查接口
     */

    /**
     * 定时同步 每天两点执行
     * */
    @Async
//    @Scheduled(cron = "0 0 2 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void timingEnterpriseRelationRiskSyn(){
        if (!openReceiving) {
            LOGGER.info("openReceiving 为false");
            return ;
        }
        this.getEnterpriseRelationRisk(new AfterloanEnterpriseinfo());
    }

    /***
     * 查询企业信息
     * @param name
     * @return
     */
    @Override
    public AfterloanEnterpriseinfo getEnterpriseInfo(String name){
        //如果数据库有就不请求第三方
        AfterloanEnterpriseinfo afterloanEnterpriseinfo=getAfterloanEnterpriseinfo(name);
        if(afterloanEnterpriseinfo != null){
            return afterloanEnterpriseinfo;
        }
        JSONObject jsonObject=responceHandler("ECIInfoVerify/GetInfo",name);
        if(jsonObject == null){
            return null;
        }
        String data=jsonObject.toJSONString();
        EnterpriseInfoAnalysis enterpriseInfoAnalysis=JSONObject.parseObject(data,EnterpriseInfoAnalysis.class);
        if(enterpriseInfoAnalysis == null){
            return null;
        }
        return objectTransformation(enterpriseInfoAnalysis);
    }

    @Override
    public Page getESAfterloanPageAll(Page page, AfterloanRiskType afterloanRiskType){
        Assert.notNull(afterloanRiskType,"参数不能为空！");
        Assert.notNull(afterloanRiskType.getEnterpriseId(),"enterpriseId 不能为空！");
        if(page == null){
            page=new Page(1,10);
        }
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        afterloanRiskType.setTenantId(tenantId);
        List<AfterloanRiskType> afterloanEnterpriseinfos=afterloanRiskTypeService.getTypeAndCount(afterloanRiskType);

        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery(TENANTID,tenantId));
        boolQueryBuilder.must(QueryBuilders.matchQuery(ENTERPRISEID,afterloanRiskType.getEnterpriseId()));
        searchSourceBuilder.query(boolQueryBuilder).sort("createTime", SortOrder.ASC)
                .from((int) ((page.getCurrent() -1) * page.getSize()))
                .size((int) page.getSize());

        List<String> apiUrls=afterloanEnterpriseinfos.stream().filter(i->!StringUtils.isEmpty(i.getApiUrl()) && i.getNumber() != null && i.getNumber().intValue() != 0)
                .map(i->dataTypeES+i.getApiUrl().toLowerCase()).collect(Collectors.toList());
        if(apiUrls == null || apiUrls.size()<=0){
            return page;
        }
        String[] apiUrlsStr=apiUrls.toArray(new String[apiUrls.size()]);
        SearchRequest searchRequest = new SearchRequest(apiUrlsStr).types(apiUrlsStr).source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            LOGGER.info("查询ES请求数据：" + searchRequest);
            searchResponse = rhlClient.search(searchRequest, RequestOptions.DEFAULT);

        } catch (Exception e) {
            LOGGER.error("ES查询异常" + e.getMessage());
        }
        if (null == searchResponse) {
            return page;
        }
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<String> dataAnalystBeanList = new ArrayList<String>();
        for (SearchHit hit : hits) {
            dataAnalystBeanList.add(hit.getSourceAsString());
        }
        page.setTotal(searchResponse.getHits().totalHits);//手动设置总记录
        page.setRecords(dataAnalystBeanList);
        return page;
    }

    /***
     * 删除公司下所有数据
     */
    @Override
    public void deleteEsDateByTypeAndEnterpriseIdOrDetails(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        Assert.notNull(afterloanEnterpriseinfo,"参数不能为空！");
        Assert.notNull(afterloanEnterpriseinfo.getIds(),"ids 不能为空！");
        if(StringUtils.isEmpty(afterloanEnterpriseinfo.getTenantId())){
            String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
            afterloanEnterpriseinfo.setTenantId(tenantId);
        }
        List<AfterloanEnterpriseinfo> afterloanEnterpriseinfos=getAll(afterloanEnterpriseinfo);
        if(afterloanEnterpriseinfos == null || afterloanEnterpriseinfos.size()<=0){
            return;
        }

        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();

        List<AfterloanRiskType> afterloanRiskTypeList=afterloanEnterpriseinfos.get(0).getAfterloanRiskTypeList();
        //查询所有文档
        List<String> apiUrls=afterloanRiskTypeList.stream().filter(i->!StringUtils.isEmpty(i.getApiUrl()) && i.getNumber() != null && i.getNumber().intValue() != 0)
                .map(i->dataTypeES+i.getApiUrl().toLowerCase()).collect(Collectors.toList());
        List<String> apiUrlsDETAILS=apiUrls.stream().map(i->i+DETAILS).collect(Collectors.toList());
        apiUrlsDETAILS=apiUrlsDETAILS.stream().filter(i->getExistsIndex(i)).collect(Collectors.toList());
        apiUrls.addAll(apiUrlsDETAILS);
        String[] apiUrlsStr=new String[apiUrls.size()];
        for(int i=0;i<apiUrls.size();i++){
            apiUrlsStr[i]=apiUrls.get(i);
        }
        DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(apiUrlsStr);
        deleteRequest.setDocTypes(apiUrlsStr);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery(TENANTID,afterloanEnterpriseinfo.getTenantId()));
        boolQueryBuilder.must(QueryBuilders.matchQuery(ENTERPRISEID,afterloanEnterpriseinfo.getIds()));
        deleteRequest.setQuery(boolQueryBuilder);
        // 操作ES
        try {
            BulkByScrollResponse resp = hclient.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
            long deleted=resp.getDeleted();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /***
     * 查询详情
     * @param afterloanRiskType
     */
    @Override
    public List<String> getEsDateByTypeAndEnterpriseIdDetails(AfterloanRiskType afterloanRiskType){
        Assert.notNull(afterloanRiskType,"参数不能为空！");
        Assert.notNull(afterloanRiskType.getEnterpriseId(),"enterpriseId 不能为空！");
        Assert.notNull(afterloanRiskType.getRiskType(),"riskType 不能为空！");
        Assert.notNull(afterloanRiskType.getRiskCode(),"riskCode 不能为空！");
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        afterloanRiskType.setTenantId(tenantId);
        List<AfterloanRiskType> afterloanEnterpriseinfos=afterloanRiskTypeService.getTypeAndCount(afterloanRiskType);
        if(afterloanEnterpriseinfos == null || afterloanEnterpriseinfos.size()<=0){
            return null;
        }
        String detailsId=afterloanRiskType.getDetailsId();
        afterloanRiskType=afterloanEnterpriseinfos.get(0);

        RestHighLevelClient rhlClient = eSconfig.getFactory().getRhlClient();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery(TENANTID,tenantId));
        boolQueryBuilder.must(QueryBuilders.matchQuery(ENTERPRISEID,afterloanRiskType.getEnterpriseId()));
        boolQueryBuilder.must(QueryBuilders.matchQuery(ID,detailsId));

        searchSourceBuilder.query(boolQueryBuilder).sort("createTime", SortOrder.ASC);
        String data=dataTypeES+afterloanRiskType.getApiUrl().toLowerCase()+DETAILS;
        if(!getExistsIndex(afterloanRiskType.getApiUrl()+DETAILS)){
            LOGGER.info("es index null :{}",data);
            return null;
        }
        SearchRequest searchRequest = new SearchRequest(data).types(data).source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            LOGGER.info("查询ES请求数据：" + searchRequest);
            searchResponse = rhlClient.search(searchRequest, RequestOptions.DEFAULT);

        } catch (Exception e) {
            LOGGER.error("ES查询异常" + e.getMessage());
        }
        if (null == searchResponse) {
            return null;
        }
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<String> dataAnalystBeanList = new ArrayList<String>();
        for (SearchHit hit : hits) {
            dataAnalystBeanList.add(hit.getSourceAsString());
        }
        return  dataAnalystBeanList;
    }

    /**
     * 企业关联风险扫描
     */
    @Override
    @Async
    public String getEnterpriseRelationRisk(AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        List<AfterloanEnterpriseinfo> afterloanEnterpriseinfos=getAll(afterloanEnterpriseinfo);
        if(afterloanEnterpriseinfos == null || afterloanEnterpriseinfos.size()<=0){
            return null;
        }
        List<AfterloanRiskNumber> afterloanRiskNumberList=new ArrayList<>();
        List<AfterloanEnterpriseinfo> afterloanEnterpriseinfosDb=new ArrayList<>();
        Date date=new Date();
        afterloanEnterpriseinfos.stream().forEach(item->{
            List<AfterloanRiskType> afterloanRiskTypeList=item.getAfterloanRiskTypeList();
            int size=afterloanRiskTypeList.size();
            if(afterloanRiskTypeList != null){
                Stream.iterate(0, i->i+1).limit(size).forEach(index->{
                    AfterloanRiskType afterloanRiskType=afterloanRiskTypeList.get(index);
                    boolean isPage=true;
                    if(afterloanRiskType.getRiskCode()==1 || afterloanRiskType.getRiskCode()==17 || afterloanRiskType.getRiskType().intValue() == 2){
                        isPage=false;
                    }
                    queryAndSave(item,afterloanRiskType,item.getEnterpriseName(),index,isPage);

                    AfterloanRiskNumber afterloanRiskNumber=new AfterloanRiskNumber();
                    afterloanRiskNumber.setNumber(afterloanRiskType.getNumber());
                    afterloanRiskNumber.setRiskTypeId(afterloanRiskType.getId());
                    afterloanRiskNumber.setEnterpriseId(item.getId());
                    afterloanRiskNumber.setTenantId(item.getTenantId());
                    afterloanRiskNumber.setCreateTime(date);
                    afterloanRiskNumber.setCreator(item.getTenantId());
                    afterloanRiskNumber.setModifyTime(date);
                    afterloanRiskNumber.setModifier(item.getTenantId());
                    afterloanRiskNumberList.add(afterloanRiskNumber);
                });
                //修改才更新
                item.setModifyTime(date);
                afterloanEnterpriseinfosDb.add(item);
            }
        });
        if(afterloanRiskNumberList != null && afterloanRiskNumberList.size()>0){
            afterloanRiskNumberService.insertSaveOrUpdateList(afterloanRiskNumberList);
        }
        //修改企业更新时间
        if(afterloanEnterpriseinfosDb != null && afterloanEnterpriseinfosDb.size()>0){
            saveOrUpdateBatch(afterloanEnterpriseinfosDb);
        }
        return null;
    }

    private boolean getExistsIndex(String code){
        String type=dataTypeES+code;
        String data=type.toLowerCase();
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();
        GetIndexRequest existsRequest = new GetIndexRequest();
        existsRequest.indices(data);//输入要判断的索引名字
        //返回值是布尔类型，判断方法是client对象下indices()方法的exists方法，在这个方法里有索引的名字；
        boolean exists=false;
        try {
            exists = hclient.indices().exists(existsRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return exists;
    }

    /***
     *
     * @param code 风险类型
     * @param name 公司名称
     * @param isPage 数据是否分页
     */
    private  void queryAndSave(AfterloanEnterpriseinfo afterloanEnterpriseinfo,AfterloanRiskType afterloanRiskType,String name,Integer code,boolean isPage){
        String apiUrl=afterloanRiskType.getApiUrl();
        if(StringUtils.isEmpty(apiUrl)){
            return;
        }
        if(isPage){
            queryPageAndSave(apiUrl,name,apiUrl,afterloanRiskType,afterloanEnterpriseinfo);
        }else{
            queryAndSave(apiUrl,name,apiUrl,afterloanRiskType,afterloanEnterpriseinfo);
        }
    }

    /***
     * JSON解析类
     */
    @Data
    static class CompanySelfRisk{
        //严重违法条目数
        private Integer SVCount;
        //失信被执行条目数
        private Integer SXCount;
        //行政处罚条目数
        private Integer APCount;
        //裁判文书条目数
        private Integer JUDCount;
        //开庭公告条目数
        private Integer CSACount;
        //司法拍卖条目数
        private Integer JSCount;
        //被执行人条目数
        private Integer ZXCount;
        //法院公告条目数
        private Integer CTACount;
        //立案数量条目数
        private Integer LACount;
        //限制消费条目数
        private Integer STCount;
        //终本案件条目数
        private Integer ENCCount;
        //环保处罚条目数
        private Integer EPCount;
        //股权出质条目数
        private Integer PLECount;
        //动产抵押条目数
        private Integer MLECount;
        //股权冻结条目数
        private Integer ASCount;
        //经营异常条目数
        private Integer EXCount;
    }

    /***
     * 分页JSON解析类
     */
    @Data
    static class Paging{
        private Integer PageSize;
        private Integer PageIndex;
        private Integer TotalRecords;
        Paging(){
            this.setPageIndex(1);
            this.setPageSize(20);
        }
    }

    /***
     * 普通查询
     * @param url
     * @param name
     * @return
     */
    private JSONObject responceHandler(String url,String name){
        if(StringUtils.isEmpty(url) || StringUtils.isEmpty(name)){
            return null;
        }
        String result=HttpUtils.HttpGet(url,"searchKey="+name);

        if(result == null){
            return null;
        }
        JSONObject jsonObject=JSONObject.parseObject(result);
        jsonObject=jsonObject.getJSONObject("Result");
        return jsonObject;
    }

    /***
     * 普通查询并保存
     * @param url
     * @param name
     * @return
     */
    private void queryAndSave(String url,String name,String code,AfterloanRiskType afterloanRiskType,AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        if(StringUtils.isEmpty(url) || StringUtils.isEmpty(name)){
            return;
        }
        String result=HttpUtils.HttpGet(url.concat("/GetList"),"searchKey="+name);
        if(result == null){
            return;
        }
        JSONObject jsonObject=JSONObject.parseObject(result);
        jsonObject=jsonObject.getJSONObject("Result");
        //数据是否存在(1-存在，0-不存在)
        Integer verifyResult=jsonObject.getInteger("VerifyResult");
        if(verifyResult == 0){
            return;
        }
        JSONArray jsonArray=jsonObject.getJSONArray("Data");
        if(jsonArray == null || jsonArray.size()<=0){
            return;
        }
        boolean falg=false;
        if(afterloanRiskType.getNumber() == null){
            falg=true;
        }else if(afterloanRiskType.getNumber().intValue() != jsonArray.size()){
            //数量有变化
            falg=true;
        }else{
            //无变化之间返回
            return;
        }
        //插入
        String type=dataTypeES+code;
        String data=type.toLowerCase();
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();

        GetIndexRequest existsRequest = new GetIndexRequest();
        existsRequest.indices(data,data+DETAILS);//输入要判断的索引名字
        //返回值是布尔类型，判断方法是client对象下indices()方法的exists方法，在这个方法里有索引的名字；
        boolean exists=false;
        try {
            exists = hclient.indices().exists(existsRequest,RequestOptions.DEFAULT);
            if(!exists){
                //进行判断返回值；
                //creataIndex(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        BulkRequest request = new BulkRequest();
        if(falg  && exists){
            DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(data,data+DETAILS);
            deleteRequest.setDocTypes(data,data+DETAILS);
            deleteRequest.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(TENANTID,afterloanEnterpriseinfo.getTenantId()))
                    .must(QueryBuilders.termQuery(ENTERPRISEID,afterloanEnterpriseinfo.getId())));
            // 操作ES
            try {
                BulkByScrollResponse resp = hclient.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
                long deleted=resp.getDeleted();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LOGGER.info("数据入录insert json str =" + jsonArray.toJSONString());
        jsonArray.stream().forEach(i->{
            JSONObject jsonObj=JSONObject.parseObject(i.toString());
            String id=jsonObj.getString("Id");
            String uuid=null;
            if(StringUtils.isEmpty(id)){
                uuid=UUID.randomUUID().toString();
            }else{
                uuid=id;
            }
            JSONObject json=new JSONObject();
            json.put(TENANTID,afterloanEnterpriseinfo.getTenantId());
            json.put(ENTERPRISEID,afterloanEnterpriseinfo.getId());
            json.put(ID,uuid);
            json.put("createTime",new Date());
            json.put("data",jsonObj.toString());
            request.add(new IndexRequest(data).type(data).id(uuid).source(json.toString(), XContentType.JSON));
        });
        try {
            BulkResponse bulkResponse = hclient.bulk(request, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse bulkItemResponse : bulkResponse) {
                    if (bulkItemResponse.isFailed()) {
                        //检索失败操作的失败
                        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                        LOGGER.error("插入索引为{}id为{}ES动作失败!", failure.getIndex(), failure.getId());
                        throw new Exception();
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("插入索引为{}的ES动作失败{}!", indexStrES, e);
            return;
        }
        afterloanRiskType.setNumber(jsonArray.size());
        return;
    }



    /***
     * 查询分页详情
     */
    private  void queryPageAndSave(String url,String name,String code,AfterloanRiskType afterloanRiskType,AfterloanEnterpriseinfo afterloanEnterpriseinfo){
        JSONArray jsonArray=responceHandlerPage(url.concat("/GetList"),name);
        if(jsonArray == null || jsonArray.size()<=0){
            return;
        }
        boolean falg=false;
        if(afterloanRiskType.getNumber() == null){
            falg=true;
        }else if(afterloanRiskType.getNumber().intValue() != jsonArray.size()){
            //数量有变化
            falg=true;
        }else{
            //无变化之间返回
            return;
        }
        //插入
        String type=dataTypeES+code;
        String data=type.toLowerCase();
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();
        GetIndexRequest existsRequest = new GetIndexRequest();
        existsRequest.indices(data,data+DETAILS);//输入要判断的索引名字
        //返回值是布尔类型，判断方法是client对象下indices()方法的exists方法，在这个方法里有索引的名字；
        boolean exists=false;
        try {
            exists = hclient.indices().exists(existsRequest,RequestOptions.DEFAULT);
            if(!exists){
                //进行判断返回值；
                //creataIndex(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(falg && exists){
            DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(data,data+DETAILS);
            deleteRequest.setDocTypes(data,data+DETAILS);
            deleteRequest.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(TENANTID,afterloanEnterpriseinfo.getTenantId()))
                    .must(QueryBuilders.termQuery(ENTERPRISEID,afterloanEnterpriseinfo.getId())));
            // 操作ES
            try {
                BulkByScrollResponse resp = hclient.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
                long deleted=resp.getDeleted();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BulkRequest request = new BulkRequest();
        BulkRequest requestDest = new BulkRequest();
        LOGGER.info("数据入录insert json str =" + jsonArray.toJSONString());
        jsonArray.stream().forEach(i->{
            JSONObject jsonObject=JSONObject.parseObject(i.toString());
            String id=jsonObject.getString("Id");
            String uuid=null;
            if(StringUtils.isEmpty(id)){
                uuid=UUID.randomUUID().toString();
            }else{
                uuid=id;
            }
            JSONObject json=new JSONObject();
            json.put(TENANTID,afterloanEnterpriseinfo.getTenantId());
            json.put(ENTERPRISEID,afterloanEnterpriseinfo.getId());
            json.put(ID,uuid);
            json.put("createTime",new Date());
            json.put("data",jsonObject.toString());
            //主
            request.add(new IndexRequest(data).type(data).id(uuid).source(json.toString(), XContentType.JSON));
            //存在详情时，id不为空
            if(!StringUtils.isEmpty(id)){
                jsonObject=responceHandlerById(url,id,afterloanRiskType,name,jsonObject);
                //父类子类公用同一ID
                if(jsonObject != null && jsonObject.size()>0){
                    json=new JSONObject();
                    json.put(TENANTID,afterloanEnterpriseinfo.getTenantId());
                    json.put(ENTERPRISEID,afterloanEnterpriseinfo.getId());
                    json.put(ID,uuid);
                    json.put("createTime",new Date());
                    json.put("data",jsonObject.toString());
                    String typedesc=data.concat(DETAILS);
                    requestDest.add(new IndexRequest(typedesc).type(typedesc).id(uuid).source(json.toString(), XContentType.JSON));
                }
            }
        });
        try {
            BulkResponse bulkResponse = hclient.bulk(request, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse bulkItemResponse : bulkResponse) {
                    if (bulkItemResponse.isFailed()) {
                        //检索失败操作的失败
                        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                        LOGGER.error("插入索引为{}id为{}ES动作失败!", failure.getIndex(), failure.getId());
                        throw new Exception();
                    }
                }
            }
            bulkResponse = hclient.bulk(requestDest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                for (BulkItemResponse bulkItemResponse : bulkResponse) {
                    if (bulkItemResponse.isFailed()) {
                        //检索失败操作的失败
                        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
                        LOGGER.error("插入索引为{}id为{}ES动作失败!", failure.getIndex(), failure.getId());
                        throw new Exception();
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("插入索引为{}的ES动作失败{}!", indexStrES, e);
            return ;
        }
        afterloanRiskType.setNumber(jsonArray.size());
    }


    public boolean creataIndex(String indexId) {
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();
        boolean isAcknowledged = false;
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexId);
        try {
            XContentBuilder mapping = jsonBuilder().
                    startObject().
                    startObject("properties").
                    startObject(TENANTID).field("type", "text").
                    endObject().
                    startObject(ENTERPRISEID).field("type", "text").
                    endObject().
                    startObject(ID).field("type", "text").
                    endObject().
                    startObject("createTime").field("type", "date").
                    endObject().
                    startObject("data").field("type", "text").
                    endObject().
                    endObject().
                    endObject();
            createIndexRequest.source(mapping);
            isAcknowledged = hclient.indices().create(createIndexRequest, RequestOptions.DEFAULT).isAcknowledged();
        } catch (Exception e) {
            LOGGER.error("创建租户id为{}的ES索引失败!", indexId);
        }
        return isAcknowledged;
    }

    //################

    /***
     * 根据ID查询详情
     * @param url
     * @param id
     * @return
     */
    private JSONObject responceHandlerById(String url,String id,AfterloanRiskType afterloanRiskType,String name,JSONObject paramJson){
        if(StringUtils.isEmpty(url) || StringUtils.isEmpty(id)){
            return null;
        }
        String param="id="+id;
        if(afterloanRiskType.getRiskCode().intValue() == 14 && afterloanRiskType.getRiskType().intValue() == 1){
            param=param.concat("&searchKey="+name);
        }
        if(afterloanRiskType.getRiskCode().intValue() == 16 && afterloanRiskType.getRiskType().intValue() == 1){
            JSONObject relatedInfo=paramJson.getJSONObject("RelatedInfo");
            String keyNo=relatedInfo.getString("KeyNo");
            param=param.concat("&KeyNo="+keyNo);
        }
        //行政处罚详情特殊处理
        if(afterloanRiskType.getRiskCode().intValue() == 3 && afterloanRiskType.getRiskType().intValue() == 1){
            url=url.concat("/GetCreditDetail");
        }else{
            url=url.concat("/GetDetail");
        }
        String result=HttpUtils.HttpGet(url,param);
        if(result == null){
            return null;
        }
        JSONObject jsonObject=JSONObject.parseObject(result);
        jsonObject=jsonObject.getJSONObject("Result");
        return jsonObject;
    }

    /***
     * 分页查询所有
     * @param url
     * @param name
     * @return
     */
    private static JSONArray responceHandlerPage(String url,String name){
        if(StringUtils.isEmpty(url) || StringUtils.isEmpty(name)){
            return null;
        }
        Paging paging=new Paging();
        String param="searchKey="+name+"&pageIndex="+paging.getPageIndex()+"&pageSize="+paging.getPageSize();
        String result=HttpUtils.HttpGet(url,param);
        if(result == null){
            return null;
        }
        JSONObject jsonObject=JSONObject.parseObject(result);
        JSONObject jsonResult=jsonObject.getJSONObject("Result");
        //数据是否存在(1-存在，0-不存在)
        Integer verifyResult=jsonResult.getInteger("VerifyResult");
        if(verifyResult == 0){
            return null;
        }
        JSONArray jsonArray=jsonResult.getJSONArray("Data");
        //存在数据查看是否分页
        paging=jsonObject.getObject("Paging",Paging.class);
        if(paging == null){
            return jsonArray;
        }else{
            Integer pageIndex=paging.getPageIndex()+1;
            Integer pageSize=paging.getPageSize();
            Integer totalRecords=paging.getTotalRecords()-pageSize;
            for (int i=1;i<=totalRecords;){
                result=HttpUtils.HttpGet(url,"searchKey="+name+"&pageIndex="+pageIndex+"&pageSize="+pageSize);
                if(result == null){
                    continue;
                }
                jsonObject=JSONObject.parseObject(result);
                jsonResult=jsonObject.getJSONObject("Result");
                //数据是否存在(1-存在，0-不存在)
                verifyResult=jsonResult.getInteger("VerifyResult");
                if(verifyResult == 0){
                    continue;
                }
                JSONArray jsonArrayPage=jsonResult.getJSONArray("Data");
                jsonArray.addAll(jsonArrayPage);
                pageIndex+=1;
                i+=pageSize;
            }
        }
        return jsonArray;
    }

    @Data
    static class EnterpriseInfoAnalysis{
        //公司名称
        String Name;
        //法人
        String OperName;
        //成立日期
        String StartDate;
        //信用代码
        String CreditCode;
        //注册资本
        String RegistCapi;
        //地址
        String Address;
        //Logo地址
        String ImageUrl;
    }

    private AfterloanEnterpriseinfo objectTransformation(EnterpriseInfoAnalysis enterpriseInfoAnalysis){
        AfterloanEnterpriseinfo afterloanEnterpriseinfo=new AfterloanEnterpriseinfo();
        afterloanEnterpriseinfo.setLarName(enterpriseInfoAnalysis.getOperName());
        String startDate=enterpriseInfoAnalysis.getStartDate();
        if(!StringUtils.isEmpty(startDate)){
            afterloanEnterpriseinfo.setEstablishTime(DateUtil.getDateFromYYYYMMDDHHmmss(startDate));
        }
        afterloanEnterpriseinfo.setEnterpriseCode(enterpriseInfoAnalysis.getCreditCode());
        afterloanEnterpriseinfo.setRegisteCapital(enterpriseInfoAnalysis.getRegistCapi());
        afterloanEnterpriseinfo.setAddress(enterpriseInfoAnalysis.getAddress());
        afterloanEnterpriseinfo.setImageUrl(enterpriseInfoAnalysis.getImageUrl());
        afterloanEnterpriseinfo.setEnterpriseName(enterpriseInfoAnalysis.getName());
        return afterloanEnterpriseinfo;

    }
}


